<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>OGM & Protocols — South America</title>
  <script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
  <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      background: #fff;
      font-family: system-ui, Segoe UI, Roboto, Arial, sans-serif;
    }
    .wrap {
      display: grid;
      grid-template-columns: 1fr 320px;
      grid-template-rows: 100%;
      height: 100vh;
      width: 100vw;
    }
    #map {
      width: 100%;
      height: 100%;
    }
    aside {
      border-left: 1px solid #eee;
      padding: 14px 14px 14px 16px;
      overflow: auto;
    }
    aside h2 {
      margin: 0 0 8px;
      font-size: 16px;
      font-weight: 600;
    }
    aside .btn {
      display: inline-block;
      margin: 8px 0 12px;
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 8px;
      cursor: pointer;
      background: #fafafa;
    }
    table.mini {
      width: 100%;
      border-collapse: collapse;
      font-size: 13px;
      margin-bottom: 14px;
    }
    table.mini th, table.mini td {
      border-bottom: 1px solid #eee;
      padding: 6px 4px;
      text-align: left;
    }
    table.mini th {
      font-weight: 600;
      background: #f9f9f9;
    }
    .muted {
      color: #666;
      font-size: 12px;
      margin-top: 8px;
    }
  </style>
</head>
<body>
<div class="wrap">
  <div id="map"></div>
  <aside>
    <h2>Status overview</h2>
    <button id="exportPng" class="btn">Export PNG</button>
    <div id="counts"></div>
    <div class="muted">Counts consider the countries listed on the map scope.</div>
  </aside>
</div>

<script>
const southAmerica = ["Argentina", "Bolivia", "Brazil", "Chile", "Colombia", "Ecuador", "Guyana", "Paraguay", "Peru", "Suriname", "Uruguay", "Venezuela"];
const centroids = {"Argentina": [-64.967, -34.0], "Bolivia": [-64.671, -16.713], "Brazil": [-53.0, -10.0], "Chile": [-71.0, -33.0], "Colombia": [-74.297, 4.57], "Ecuador": [-78.183, -1.831], "Guyana": [-58.93, 4.86], "Paraguay": [-58.443, -23.442], "Peru": [-75.015, -9.19], "Suriname": [-55.911, 3.92], "Uruguay": [-55.766, -32.523], "Venezuela": [-66.59, 6.423]};
const listedCountries = ["Argentina", "Bolivia", "Brazil", "Chile", "Colombia", "Ecuador", "Guyana", "Peru", "Venezuela"];
const dataInfo = {"Argentina": {"Cartagena": "Not a party", "Nagoya": "Party", "Nagoya_KL": "Not a party", "Cultivation": "Allowed", "Import": "Allowed"}, "Bolivia": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Not a party", "Cultivation": "Allowed", "Import": "Allowed"}, "Brazil": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Not a party", "Cultivation": "Allowed", "Import": "Allowed"}, "Chile": {"Cartagena": "Not a party", "Nagoya": "Not a party", "Nagoya_KL": "Not a party", "Cultivation": "Allowed", "Import": "Allowed"}, "Colombia": {"Cartagena": "Party", "Nagoya": "Not a party", "Nagoya_KL": "Party", "Cultivation": "Allowed", "Import": "Allowed"}, "Ecuador": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Not a party", "Cultivation": "Prohibited", "Import": "Allowed"}, "Guyana": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Not a party", "Cultivation": "Allowed", "Import": "Allowed"}, "Peru": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Party", "Cultivation": "Prohibited", "Import": "Prohibited"}, "Venezuela": {"Cartagena": "Party", "Nagoya": "Party", "Nagoya_KL": "Party", "Cultivation": "Prohibited", "Import": "Prohibited"}};
const dx = 0.9;

function tooltip(country){
  const d = dataInfo[country] || {};
  return `<b>${country}</b><br>
  Cartagena Protocol: ${d.Cartagena ?? "—"}<br>
  Nagoya Protocol: ${d.Nagoya ?? "—"}<br>
  Nagoya–Kuala Lumpur: ${d.Nagoya_KL ?? "—"}<br>
  GMO cultivation: ${d.Cultivation ?? "—"}<br>
  GMO import: ${d.Import ?? "—"}`;
}

function layerPoints(type){
  const lons=[], lats=[], texts=[];
  for (const c of southAmerica){
    if(!centroids[c]) continue;
    const [lon,lat]=centroids[c];
    const info=dataInfo[c]||{};
    let add=false, lonShift=0;
    switch(type){
      case "cult_allowed": add=(info.Cultivation==="Allowed"); break;
      case "cult_prohib": add=(info.Cultivation==="Prohibited"); break;
      case "imp_allowed": add=(info.Import==="Allowed"); lonShift=dx; break;
      case "imp_prohib": add=(info.Import==="Prohibited"); lonShift=dx; break;
      case "nag_party": add=(info.Nagoya==="Party"); lonShift=-dx; break;
      case "nag_not": add=(info.Nagoya==="Not a party"); lonShift=-dx; break;
      case "cart_party": add=(info.Cartagena==="Party"); lonShift=-2*dx; break;
      case "cart_not": add=(info.Cartagena==="Not a party"); lonShift=-2*dx; break;
      case "kl_party": add=(info.Nagoya_KL==="Party"); lonShift=2*dx; break;
      case "kl_not": add=(info.Nagoya_KL==="Not a party"); lonShift=2*dx; break;
    }
    if(add){lons.push(lon+lonShift); lats.push(lat); texts.push(tooltip(c));}
  }
  return {lons,lats,texts};
}

const baseMap = {
  type:"choropleth",
  locationmode:"country names",
  locations:southAmerica,
  z:southAmerica.map(c=>listedCountries.includes(c)?1:0),
  colorscale:[[0,"#333333"],[0.000001,"#333333"],[0.999999,"#2E7D32"],[1,"#2E7D32"]],
  showscale:false,
  hovertemplate:"%{location}<extra></extra>"
};

const layers = [["GMO cultivation \u2014 Allowed", "circle", "cult_allowed"], ["GMO cultivation \u2014 Prohibited", "circle-open", "cult_prohib"], ["GMO import \u2014 Allowed", "square", "imp_allowed"], ["GMO import \u2014 Prohibited", "square-open", "imp_prohib"], ["Nagoya Protocol \u2014 Party", "star", "nag_party"], ["Nagoya Protocol \u2014 Not a party", "star-open", "nag_not"], ["Cartagena Protocol \u2014 Party", "triangle-up", "cart_party"], ["Cartagena Protocol \u2014 Not a party", "triangle-up-open", "cart_not"], ["Nagoya\u2013Kuala Lumpur \u2014 Party", "diamond", "kl_party"], ["Nagoya\u2013Kuala Lumpur \u2014 Not a party", "diamond-open", "kl_not"]];
const traces = [baseMap];
for (const [name,symbol,key] of layers){
  const {lons,lats,texts} = layerPoints(key);
  traces.push({
    type:"scattergeo",
    lon:lons, lat:lats, text:texts,
    mode:"markers",
    hovertemplate:"%{text}<extra></extra>",
    name,
    marker:{symbol, size:11, line:{width:1, color:"white"}}
  });
}

function computeCounts() {
  const protStatuses = (field) => {
    const counts = {};
    for (const c of southAmerica) {
      const v = (dataInfo[c]||{})[field] || "—";
      if (v !== "—") {  // exclude em dash
        counts[v] = (counts[v]||0) + 1;
      }
    }
    return counts;
  };
  const binStatuses = (field) => {
    const counts = {};
    for (const c of southAmerica) {
      const v = (dataInfo[c]||{})[field] || "—";
      if (v !== "—") {
        counts[v] = (counts[v]||0) + 1;
      }
    }
    return counts;
  };

  return {
    cartagena: protStatuses("Cartagena"),
    nagoya_kl: protStatuses("Nagoya_KL"),
    nagoya: protStatuses("Nagoya"),
    cultivation: binStatuses("Cultivation"),
    imports: binStatuses("Import")
  };
}

function tableFromCounts(title, obj) {
  const rows = Object.entries(obj).sort((a,b)=>a[0].localeCompare(b[0]));
  let html = `<h2>${title}</h2><table class="mini"><thead><tr><th>Status</th><th>Count</th></tr></thead><tbody>`;
  for (const [k,v] of rows) {
    html += `<tr><td>${k}</td><td>${v}</td></tr>`;
  }
  html += `</tbody></table>`;
  return html;
}

function renderCounts() {
  const c = computeCounts();
  const el = document.getElementById("counts");
  el.innerHTML = ""
    + tableFromCounts("Cartagena Protocol", c.cartagena)
    + tableFromCounts("Nagoya–Kuala Lumpur", c.nagoya_kl)
    + tableFromCounts("Nagoya Protocol", c.nagoya)
    + tableFromCounts("GMO cultivation", c.cultivation)
    + tableFromCounts("GMO import", c.imports);
}

const layout = {
  title: { text: "Green - American Andean or ACTO | Dark gray - not American Andean or ACTO", x:0.01, xanchor:"left" },
  geo: { scope:"south america", showcountries:true, countrycolor:"white", showcoastlines:false, showframe:false, projection:{type:"mercator"} },
  margin: { l:0, r:0, t:120, b:0 },
  legend: { title: { text:"Symbols" }, orientation:"h", yanchor:"bottom", y:0.01, xanchor:"left", x:0.02 },
  updatemenus: [
    // Cartagena (first)
    {
      type: "dropdown", showactive: true, x: 0.02, y: 0.98, xanchor: "left", yanchor: "top",
      bgcolor: "rgba(255,255,255,0.95)", bordercolor: "#ccc",
      buttons: [
        {label:"Cartagena: All", method:"update", args:[{visible: [true, true, true, true, true, true, true, true, true, true, true]}, {}]},
        {label:"Cartagena: Party", method:"update", args:[{visible: [true, false, false, false, false, false, false, true, false, false, false]}, {}]},
        {label:"Cartagena: Not a party", method:"update", args:[{visible: [true, false, false, false, false, false, false, false, true, false, false]}, {}]},
      ]
    },
    // Nagoya–Kuala Lumpur (second)
    {
      type: "dropdown", showactive: true, x: 0.02, y: 0.82, xanchor: "left", yanchor: "top",
      bgcolor: "rgba(255,255,255,0.95)", bordercolor: "#ccc",
      buttons: [
        {label:"Nagoya–Kuala Lumpur: All", method:"update", args:[{visible: [true, true, true, true, true, true, true, true, true, true, true]}, {}]},
        {label:"Nagoya–Kuala Lumpur: Party", method:"update", args:[{visible: [true, false, false, false, false, false, false, false, false, true, false]}, {}]},
        {label:"Nagoya–Kuala Lumpur: Not a party", method:"update", args:[{visible: [true, false, false, false, false, false, false, false, false, false, true]}, {}]},
      ]
    },
    // Nagoya (third)
    {
      type: "dropdown", showactive: true, x: 0.02, y: 0.66, xanchor: "left", yanchor: "top",
      bgcolor: "rgba(255,255,255,0.95)", bordercolor: "#ccc",
      buttons: [
        {label:"Nagoya: All", method:"update", args:[{visible: [true, true, true, true, true, true, true, true, true, true, true]}, {}]},
        {label:"Nagoya: Party", method:"update", args:[{visible: [true, false, false, false, false, true, false, false, false, false, false]}, {}]},
        {label:"Nagoya: Not a party", method:"update", args:[{visible: [true, false, false, false, false, false, true, false, false, false, false]}, {}]},
      ]
    },
    // GMO cultivation (fourth)
    {
      type: "dropdown", showactive: true, x: 0.02, y: 0.5, xanchor: "left", yanchor: "top",
      bgcolor: "rgba(255,255,255,0.95)", bordercolor: "#ccc",
      buttons: [
        {label:"GMO cultivation: All", method:"update", args:[{visible: [true, true, true, true, true, true, true, true, true, true, true]}, {}]},
        {label:"GMO cultivation: Allowed", method:"update", args:[{visible: [true, true, false, false, false, false, false, false, false, false, false]}, {}]},
        {label:"GMO cultivation: Prohibited", method:"update", args:[{visible: [true, false, true, false, false, false, false, false, false, false, false]}, {}]},
      ]
    },
    // GMO import (fifth)
    {
      type: "dropdown", showactive: true, x: 0.02, y: 0.34, xanchor: "left", yanchor: "top",
      bgcolor: "rgba(255,255,255,0.95)", bordercolor: "#ccc",
      buttons: [
        {label:"GMO import: All", method:"update", args:[{visible: [true, true, true, true, true, true, true, true, true, true, true]}, {}]},
        {label:"GMO import: Allowed", method:"update", args:[{visible: [true, false, false, true, false, false, false, false, false, false, false]}, {}]},
        {label:"GMO import: Prohibited", method:"update", args:[{visible: [true, false, false, false, true, false, false, false, false, false, false]}, {}]},
      ]
    }
  ]
};

Plotly.newPlot("map", traces, layout, {displayModeBar:true}).then(() => {
  renderCounts();
});

// Export PNG
document.getElementById("exportPng").addEventListener("click", async () => {
  const gd = document.getElementById("map").querySelector(".js-plotly-plot");
  const dataUrl = await Plotly.toImage(gd, {format: "png", height: 1080, width: 1920});
  const a = document.createElement("a");
  a.href = dataUrl;
  a.download = "OGM_Protocols_Map.png";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
});
</script>
</body>
</html>
